package com.javasm.mingming.common.utils;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Component;

/**
 * @author javasm
 * @version 0.1
 * @className SmsUtil
 * @descriptioin:
 * @date 2025/1/16 14:34
 * @since jdk11
 */
@Component
public class SmsUtil {
    private static Logger log = LogManager.getLogger(SmsUtil.class);
    //客户端对象
    private static Client client;
    //你的  AccessKey ID
    private final static String accessKeyId = "LTAI5tLRwayb3fyGS7QdJ9sm";
    //你的 AccessKey Secret
    private final static String accessKeySecret = "6tswbL48oz2hL235lAj5gVX1r7HClj";

    /**
     * 对外公开的调用方法
     * @param uphone 手机号
     * @param code  验证码
     */
    public void sendSms(String uphone, String code) {
        //组装请求对象
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setSignName("王绍成")
                .setPhoneNumbers(uphone)
                .setTemplateCode("SMS_109030028")
                .setTemplateParam("{\"code\":" + code + "}");
        //运行选项
        RuntimeOptions runtime = new RuntimeOptions();
        try {
            //发送短信，返回响应信息
            SendSmsResponse sendSmsResponse = createClient().sendSmsWithOptions(sendSmsRequest, runtime);
            //输出日志，查看返回信息
            log.info(sendSmsResponse.body.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    private Client createClient() throws Exception {
        if (client != null) {
            return client;
        }
        Config config = new Config()
                .setAccessKeyId(accessKeyId)
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        client = new Client(config);
        return client;
    }


}
